package com.yunxin.core.customer.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.core.admin.treeUtil.AdminOptionDTO;
import com.yunxin.core.customer.domain.CustomerTag;
import com.yunxin.core.customer.domain.TagInfo;
import com.yunxin.core.customer.dto.AddTagDto;
import com.yunxin.core.customer.dto.UpdateTagDto;
import com.yunxin.core.customer.mapper.CustomerTagMapper;
import com.yunxin.core.customer.service.CustomerTagService;
import com.yunxin.core.customer.service.TagInfoService;
import com.yunxin.core.customer.mapper.TagInfoMapper;
import com.yunxin.core.wechat.domain.WechatTagInfo;
import com.yunxin.core.wechat.mapper.WechatFollowCustomerMapper;
import com.yunxin.core.wechat.mapper.WechatTagInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【tag_info(标签表)】的数据库操作Service实现
 * @createDate 2024-05-22 17:11:04
 */
@DS("crm")
@Service
public class TagInfoServiceImpl extends ServiceImpl<TagInfoMapper, TagInfo>
        implements TagInfoService {

    @Autowired
    private CustomerTagService customerTagService;

    @Autowired
    private WechatFollowCustomerMapper wechatFollowCustomerMapper;

    @Autowired
    private WechatTagInfoMapper wechatTagInfoMapper;


    @Override
    public List<AdminOptionDTO<Long>> listDeptOptions(Long customerId, Integer teamId) {

        ArrayList<AdminOptionDTO<Long>> list = new ArrayList<>();
        List<TagInfo> tagList = baseMapper.selectList(new LambdaQueryWrapper<TagInfo>().eq(TagInfo::getTeamId,teamId));
        // 所有的标签
        Set<Long> tagIds = tagList.stream().map(TagInfo::getId).collect(Collectors.toSet());
        Set<Long> parentIds = tagList.stream().map(TagInfo::getParentId).collect(Collectors.toSet());
        List<Long> rootIds = CollUtil.subtractToList(parentIds, tagIds);
        for (Long rootId : rootIds) {
            list.addAll(recurTagTreeOptions(rootId, tagList));
        }
        return list;
    }

    @Override
    public void addTag(AddTagDto addTagDto) {
        TagInfo tagInfo=new TagInfo();
        tagInfo.setTeamId(addTagDto.getTeamId());
        int level=1;
        if (!ObjectUtils.isEmpty(addTagDto.getParentId())){
            tagInfo.setParentId(addTagDto.getParentId());
            TagInfo parentTag = this.getById(addTagDto.getParentId());
            if (ObjectUtils.isEmpty(parentTag)){
                throw new BusinessException("父类未找到资源");
            }
            if (parentTag.getLevel()==2){
                throw new BusinessException("标签最多两级");
            }
            level=level+parentTag.getLevel();
            tagInfo.setTreePath(parentTag.getTreePath()+","+parentTag.getId());
        }
        tagInfo.setLevel(level);
        tagInfo.setName(addTagDto.getName());
        tagInfo.setCreator(addTagDto.getCreator().toString());
        this.save(tagInfo);
    }

    @Override
    public void updateTag(UpdateTagDto updateTagDto) {
        LambdaUpdateWrapper<TagInfo>  updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.eq(TagInfo::getId,updateTagDto.getId())
                .set(TagInfo::getName,updateTagDto.getName())
                .set(TagInfo::getEditor,updateTagDto.getEditor().toString());
        this.update(updateWrapper);
    }

    @Override
    public void deleteTag(Long tagId) {
        LambdaQueryWrapper<TagInfo> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(TagInfo::getParentId,tagId);
        List<TagInfo> list = this.list(queryWrapper);
        List<Long> tagIds=new ArrayList<>();
        if (!list.isEmpty()){
            List<Long> sonTagIds = list.stream().map(i -> i.getId()).toList();
            tagIds.addAll(sonTagIds);
        }
        tagIds.add(tagId);
        boolean b = this.removeBatchByIds(tagIds);
        if (b){
            LambdaQueryWrapper<CustomerTag> customerTagLambdaQueryWrapper=new LambdaQueryWrapper<>();
            customerTagLambdaQueryWrapper.in(CustomerTag::getTagInfoId,tagIds);
            customerTagService.remove(customerTagLambdaQueryWrapper);
        }
    }

    @Override
    public List<Long> listCustomerTagOptions(Long customerId) {
        LambdaQueryWrapper<CustomerTag> customerTagLambdaQueryWrapper=new LambdaQueryWrapper<>();
        customerTagLambdaQueryWrapper.eq(CustomerTag::getCustomerInfoId,customerId);
        List<CustomerTag> list = customerTagService.list(customerTagLambdaQueryWrapper);
        list.stream().map(i->i.getTagInfoId()).toList();
        return list.stream().map(i->i.getTagInfoId()).toList();
    }

    @Override
    public List<AdminOptionDTO<String>> listQwCustomerTagOptions(Long wechatCustomerId) {
        ArrayList<AdminOptionDTO<String>> list = new ArrayList<>();
        String wechatTagIds =  wechatFollowCustomerMapper.listWechatCustomerTag(wechatCustomerId);
        List<String> TagInfoIds = JSON.parseArray(wechatTagIds, String.class);
        if (CollUtil.isEmpty(TagInfoIds)){
            return list;
        }
        List<WechatTagInfo> tagList = wechatTagInfoMapper.selectList(new LambdaQueryWrapper<WechatTagInfo>().in(WechatTagInfo::getTagId, TagInfoIds));
        Set<String> parentIds = tagList.stream().map(WechatTagInfo::getWechatGroupId).collect(Collectors.toSet());
        Set<WechatTagInfo> infos = new HashSet<>(wechatTagInfoMapper.selectList(new LambdaQueryWrapper<WechatTagInfo>().in(WechatTagInfo::getTagId, parentIds)));
        tagList.addAll(infos);

        Set<String> collect = tagList.stream().map(WechatTagInfo::getWechatGroupId).collect(Collectors.toSet());
        Set<String> longs = tagList.stream().map(WechatTagInfo::getTagId).collect(Collectors.toSet());
        List<String> rootIds = CollUtil.subtractToList(collect, longs);
        for (String rootId : rootIds) {
            list.addAll(recurWeChatTagTreeOptions(rootId, tagList));
        }
        return list;
    }

    /**
     * 递归生成标签层级列表
     *
     * @param parentId parentId
     * @param tagIds   tagIds
     * @return List<OptionResponse < Long>>
     */
    private List<AdminOptionDTO<Long>> recurTagTreeOptions(long parentId, List<TagInfo> tagIds) {
        return CollUtil.emptyIfNull(tagIds).stream()
                .filter(tag -> tag.getParentId().equals(parentId))
                .map(tag -> {
                    AdminOptionDTO<Long> optionDTO = new AdminOptionDTO<>(tag.getId(), tag.getName(),tag.getLevel());
                    List<AdminOptionDTO<Long>> children = recurTagTreeOptions(tag.getId(), tagIds);
                    if (CollUtil.isNotEmpty(children)) {
                        optionDTO.setChildren(children);
                    }
                    return optionDTO;
                }).toList();
    }

    private List<AdminOptionDTO<String>> recurWeChatTagTreeOptions(String parentId,  List<WechatTagInfo>  tagIds) {
        return CollUtil.emptyIfNull(tagIds).stream()
                .filter(tag -> tag.getWechatGroupId().equals(parentId))
                .map(tag -> {
                    AdminOptionDTO<String> optionDTO = new AdminOptionDTO<>(tag.getTagId(), tag.getTagName(),tag.getLevel());
                    List<AdminOptionDTO<String>> children = recurWeChatTagTreeOptions(tag.getTagId(), tagIds);
                    if (CollUtil.isNotEmpty(children)) {
                        optionDTO.setChildren(children);
                    }
                    return optionDTO;
                }).toList();
    }

}




